package com.chenjian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chenjian.common.CommonVO;
import com.chenjian.common.enums.RESPONSE_ENUM;
import com.chenjian.common.utils.BindResultUtils;
import com.chenjian.entity.User;
import com.chenjian.exceptiom.CommonException;
import com.chenjian.service.UserService;
import com.chenjian.vo.UserAddVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired

    private UserService userServiceImpl;

    @PostMapping(value = "/add")
    public Object addUser(@RequestBody @Validated UserAddVo userAddVo, BindingResult bindingResult) {
        BindResultUtils.checkBindingResult(bindingResult);
        User user = new User();
        BeanUtils.copyProperties(userAddVo, user);
        userServiceImpl.save(user);
        return new CommonVO<>(user);
    }

    @DeleteMapping(value = "/del/{id}")
    public Object userDel(@PathVariable Long id) {
        User user = userServiceImpl.getById(id);
        if (null != user) {
            //del
            boolean removeById = userServiceImpl.removeById(user.getId());
            new CommonVO<>(removeById);
        }
        return new CommonVO<>(RESPONSE_ENUM.FAIL_404.getCode(), "查无此人");

    }

    @PutMapping(value = "/update/{id}")
    public Object updateUser(@PathVariable Long id,
                             @RequestBody @Validated UserAddVo userAddVo,
                             BindingResult bindingResult) {
        BindResultUtils.checkBindingResult(bindingResult);
        User user = userServiceImpl.getById(id);
        if (null != user) {
            BeanUtils.copyProperties(userAddVo, user);
            userServiceImpl.updateById(user);
            return user;
        }
        throw new CommonException("数据异常", RESPONSE_ENUM.FAIL_404.getCode());

    }

    @GetMapping(value = "/find/{id}")
    public Object findById(@PathVariable Long id) {
        User user = userServiceImpl.getById(id);
        if (null != user) {
            return new CommonVO<>(user);
        }
        throw new CommonException("数据异常", RESPONSE_ENUM.FAIL_404.getCode());
    }

    @GetMapping(value = "/find/or/del/{id}")
    public Object findDeletedById(@PathVariable Long id) {
        User queryUser = new User();
        queryUser.setId(id);
        List<User> user = userServiceImpl.getByUserWithQueryUser(queryUser);
        if (null != user) {
            return new CommonVO<>(user);
        }
        throw new CommonException("数据异常", RESPONSE_ENUM.FAIL_404.getCode());
    }


}
